package com.meixiang.activity.account.myShopper;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.google.gson.reflect.TypeToken;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.personalCenter.AllOrderAdapter;
import com.meixiang.entity.myOrder.MyOrderDetail;
import com.meixiang.entity.myOrder.RefundList;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 全部订单
 * @author yinsujun  Created at 2016/5/6 13:42
 */
public class MyAllOrderActivity extends BaseActivity {
    @Bind(R.id.swipe_target)
    RecyclerView mRecycler;
    @Bind(R.id.refresh)
    SwipeToLoadLayout swipeRefresh;
    private AllOrderAdapter orderAdapter;
    private String orderStatus, orderState;
    private int pageNo = 1, pageSize = 10,totalPage=0;
    private boolean isRefresh = true;
    private DetailBroadCast broadCast;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_all_order);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        registerBroadCast();
        setEvent();
    }
    private void registerBroadCast(){
        broadCast=new DetailBroadCast();
        IntentFilter intentFilter=new IntentFilter(GlobalType.ORDER_DETAIL_OPERATION);
        registerReceiver(broadCast,intentFilter);
    }

    @Override
    protected void initTitle() {
        setTitle("全部订单");
        orderStatus = getIntent().getStringExtra("status");
        if (!AbStrUtil.isEmpty(orderStatus)) {
            setTitle(orderStatus);
        }

    }

    @Override
    protected void initView() {
        orderAdapter = new AllOrderAdapter(this, orderStatus);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecycler.setLayoutManager(linearLayoutManager);
        mRecycler.setAdapter(orderAdapter);


    }

    /**
     * orderState 	String 	必填 	10 		:订单状态 //10:待付款;/ 30:待收货;/ 40:待评价/交易完成
     * pageSize 	String 	必填 	10 	10 	每页大小
     * pageNo
     *
     * 待收货：
     * orderState:30   对应状态 orderStatus:20/30
     *待付款
     * orderState:10
     * 待评价：
     * orderStatus:60  对应状态 orderStatus:40 evaluation_status:0
     * 交易完成
     * orderStatus:40
     */
    private void getData() {
        if(isRefresh==true){
            status.showLoading();
        }
        String url;
        url = Config.GET_MY_ALL_ORDER;
        HttpUtils.isAnalog=false;
        HttpParams params = new HttpParams();
        if (!AbStrUtil.isEmpty(orderStatus)) {
            if ("待付款".equals(orderStatus)) {
                orderState = "10";
            } else if ("待收货".equals(orderStatus)) {
                orderState = "30";
            } else if ("待评价".equals(orderStatus)) {
                //40 || ("退款/售后").equals(orderStatus)
                orderState = "60";
            }
        }
        if("退款/售后".equals(orderStatus)){
           url=Config.GET_MY_SALE_ORDER_LIST;
        }
        params.put("orderState", orderState);
        params.put("pageSize", pageSize + "");
        params.put("pageNo", pageNo + "");
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                status.removeView();
                onCompleteRefresh();
                if(result!=null){
                    JSONArray orderList;
                    List<MyOrderDetail> orderDetails=new ArrayList<MyOrderDetail>();
                    if("退款/售后".equals(orderStatus)){
                        orderList=result.optJSONArray("refundList");
                        /**
                         *
                         /**
                         * refundId : 退款记录ID
                         * orderId : 订单id
                         * refundSn : 退款编号
                         * refundState : 状态:1审核申请中,2正在退款中,3退款成功
                         * refundAmount : 退款金额
                         * goodsNum : 退货数量
                         * storeId : 店铺编号
                         * storeName : 店铺名称
                         * goodsPrice : 商品价格--
                         * goodsImage : 商品图片--
                         * recId : 编号
                         * goodsId : 商品编号--
                         * goodsName : 商品名称--
                         * specId : 商品规格编号
                         * specInfo : ["补水单品","均码"]
                         */
                        for(int i=0;i<orderList.length();i++){
                            RefundList refund=AbJsonUtil.fromJson(orderList.optJSONObject(i).toString(),RefundList.class);
                            MyOrderDetail orderDetail = new MyOrderDetail();
                            orderDetail.setRefundId(refund.getRefundId());
                            orderDetail.setOrderId(refund.getOrderId());
                            orderDetail.setOrderSn(refund.getRefundSn());
                            orderDetail.setOrderState(refund.getRefundState());
                            orderDetail.setOrderAmount(refund.getRefundAmount());
                            orderDetail.setStoreName(refund.getStoreName());
                            orderDetail.setStoreId(refund.getStoreId());
                            List<MyOrderDetail.OrderGoodsListBean> orderGoodList=new ArrayList<>();
                            MyOrderDetail.OrderGoodsListBean orderGoods=new MyOrderDetail.OrderGoodsListBean();
                            orderGoods.setGoodsImage(refund.getGoodsImage());
                            orderGoods.setGoodsPrice(refund.getGoodsPrice());
                            orderGoods.setGoodsName(refund.getGoodsName());
                            orderGoods.setGoodsId(refund.getGoodsId());
                            orderGoods.setGoodsNum(refund.getGoodsNum());
                            orderGoods.setSpecInfo(refund.getSpecInfo());
                            orderGoods.setSpecId(refund.getSpecId());
                            orderGoods.setRefundState(refund.getRefundState());
                            orderGoodList.add(orderGoods);
                            orderDetail.setOrderGoodsList(orderGoodList);
                            orderDetails.add(orderDetail);
                        }
                    }else{
                        orderList = result.optJSONArray("orderList");
                        orderDetails = AbJsonUtil.fromJson(orderList.toString(), new TypeToken<List<MyOrderDetail>>() {
                        });
                    }
                    totalPage=result.optInt("totalPage");
                    if(totalPage==0){
                        status.showNoData("您还没有相关的订单");
                    }
                    if(!AbStrUtil.isEmpty(orderList.toString())){
                        if(isRefresh==true){
                            orderAdapter.clear();
                        }
                        orderAdapter.addAll(orderDetails);
                    }
                }else{
                    status.showNoData("您还没有相关的订单");
                }
            }

            @Override
            public void onError(String code, String message) {
                status.removeView();
                onCompleteRefresh();
                Tool.showTextToast(context, message);
                status.showNoNewWork(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        swipeRefresh.setRefreshing(true);
                    }
                });

            }
        });
    }


    @Override
    protected void setData() {
        getData();
    }
    public void onRefresh(){
        swipeRefresh.setRefreshing(true);
    }

    private void onCompleteRefresh() {
        if (swipeRefresh != null) {
            if (isRefresh == true) {
                swipeRefresh.setRefreshing(false);
            } else {
                swipeRefresh.setLoadingMore(false);
            }
        }
    }

    private void setEvent() {
        swipeRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                isRefresh=false;
                pageNo++;
                if(pageNo>totalPage){
                    swipeRefresh.setLoadingMore(false);
                    return;
                }
                getData();

            }
        });
        swipeRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh=true;
                pageNo = 1;
                getData();
            }
        });
    }

    @Override
    public void onClick(View v) {

    }
    private class DetailBroadCast extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
//            String orderId = intent.getStringExtra("orderId");
            swipeRefresh.setRefreshing(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadCast);
    }
}
